/*
* @author: WJ
* @description: 1.角色管理模块，角色查、增、改、删
*   新增角色：需要选择四大模块中的一个，然后出现对应权限选择项。
*  功能点： add - 新增角色  mod - 查询后编辑角色 del- 查询后删除角色 所以mod和del都是需要先有查询权限（可以前端控制）
*          search - 查询角色 点击后数据表格才会呈现
*  数据呈现：Table ->  序号 角色名 角色所属模块  操作 角色明细权限
* 20180817 add的对话框 -- 选择角色类型后，才出现操作权限项
* 20180823 safe选项标识是否可以修改
*/
<template>
    <div class="sys-page">
        <!--<el-button type="success" @click="refresh()" round style="float:right; margin-top:10px;" icon="el-icon-refresh">刷新</el-button>-->
        <!--<el-button type="primary" round icon="el-icon-arrow-left" style="float:right; margin-right:10px; margin-top:10px;" @click="singleAdd()">新增角色</el-button>-->
        <!--<app-notes>一个角色只能属于一个功能模块（系统/安全/业务/审计）。</app-notes>-->
        <!-- 搜索 -->
        <el-row>
            <el-col :span="20">
                <!-- <app-search>
                    <el-form :inline="true" :model="searchForm">
                        <el-form-item>
                            <el-input v-model="searchForm.roleId" placeholder="请输入角色Id"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="search">查询</el-button>
                        </el-form-item>
                    </el-form>
                </app-search> -->
            </el-col>
            <el-col :span="4">
                <!-- 工具条 -->
                </el-col>
        </el-row>
        <!--增加、修改角色表单-->
        <el-dialog :title="dialogTitle" :visible.sync="dialogAddFormVisible" width='50%'
            :fullscreen='false'>
            <el-form :model="addForm" ref="addForm" :rules="addRules" class="">
            <el-row>
              <el-col  :span="12">
                <el-form-item prop="roleName" label="角色名称"
                              :label-width="formLabelWidth">
                  <el-input ref="roleName" v-model="mroleName"
                            placeholder="请输入角色名称"></el-input>
                </el-form-item>
              </el-col>
              <el-col  :span="12">
                <el-form-item prop="roleType" label="角色类型" :label-width="formLabelWidth">
                  <el-select v-model="mroleType" placeholder="请选择角色类型" @change='currentSel'>
                    <el-option v-for="item in userTypeOptions"
                               :key="item.value"
                               :label="item.text"
                               :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

             <el-form-item prop="roleOperate" label="操作权限" :label-width="formLabelWidth">
                <el-checkbox-group v-model="roleOperate">
                <el-checkbox  v-for="item in userRoleOperations"
                :key="item.id" :label="item.id" border size="small" @change="onSelect">
                {{item.name}}</el-checkbox>
            </el-checkbox-group>

            </el-form-item>
            <!--end-->
            </el-form>
            <div slot="footer" class="dialog-footer">
            <el-button @click="dialogAddFormVisible = false">取 消</el-button>
            <template v-if="dialogAddOrMod=='add'">
                <el-button type="primary"   v-loading="loading"
                @click.native.prevent="singleAddCommit()">确 定</el-button>
            </template>
            <template v-if="dialogAddOrMod=='mod'">
                <el-button type="primary"
                @click.native.prevent="singleModCommit()">确 定</el-button>
            </template>
            </div>
        </el-dialog>
        <!--end add & mod-->
        <!-- 表格体 -->
            <el-table v-loading="loading" :data="tableData.body" :row-class-name="tableRowClassName" border >
                <el-table-column type="expand">
                  <template slot-scope="props">
                    <el-form label-position="left" inline class="demo-table-expand">
                      <el-form-item label="角色编码" >
                        <span>{{ props.row.rid }}</span>
                      </el-form-item>
                      <el-form-item label="角色名称">
                        <span>{{ props.row.roleName }}</span>
                      </el-form-item>
                      <el-form-item label="所属类型">
                        <span>{{ typeFormatter(props.row, null, null) }}</span>
                      </el-form-item>

                      <el-form-item label="关联权限集合" style="margin-right: 0; margin-bottom: 0; width:100%;">
                        <span style="font-size:15px;color:orange;">{{ GLOBAL.getPermissionNameList(props.row.rolePrems) }}</span>
                      </el-form-item>
                    </el-form>
                  </template>
                </el-table-column>

                <el-table-column type="index" label="序号" width="64" align="center"></el-table-column>
                <el-table-column style="background-color:16#123456" label="数据安全" width="120" align="center">
                   <template slot-scope="scope">
                        <div v-if="scope.row.safe==false">
                            <i class="el-icon-warning"></i>
                            <span style="color:red"> 数据异常</span>
                        </div>
                        <div v-else-if="scope.row.safe==true">
                            <i class="el-icon-success"></i>
                            <span style="color:green">数据完整</span>
                        </div>
                  </template>
                </el-table-column>
               <!--  <el-table-column v-for="(item,index) in tableData.head" :prop="item.key" :label="item.name" align="center" sortable :key="index"></el-table-column> -->

                 <el-table-column label="角色编码" align="center" width="250" prop="rid" >
                </el-table-column> <el-table-column label="角色名称" align="center" width="250" prop="roleName">
                </el-table-column>
                 <el-table-column label="所属类型" align="center" width="180" prop="roleType" :formatter="typeFormatter">
                </el-table-column>

                <el-table-column label="操作" align="center" >
                    <template slot-scope="scope">
                        <el-button :disabled="scope.row.safe==false" v-if="true" type="text" size="middle" @click="editRole(scope.row)">编辑</el-button>
                        <el-button :disabled="scope.row.safe==false" v-if="true" type="text" size="middle" @click="confirmDelete(scope.row)" >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
             <div align="center">
              <el-pagination
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  :current-page="currentPage"
                  :page-sizes="[10, 20, 30, 40]"
                  :page-size="pageSize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="totalCount">
              </el-pagination>
          </div>
    </div>
</template>

<script>
export default {
   inject: ['reload', 'controlObj'],
    name: 'role',
    data() {

        var validateRoleName = (rule, value, callback) => {

            if (this.mroleName === '') {
                callback(new Error('请输入角色名称'))
            }  else {
                this.validIpeffective = true;
                callback()
            }
        }
        var validateRoleType = (rule, value, callback) => {

            if (this.mroleType === '') {
                callback(new Error('请选择角色类型'))
            }  else {
                callback()
            }
        }

        return {
             pageNum: 1,
            dataCount: null,
            totalCount: 1000,
            pageSize: 10,
            currentPage: 1,
            start: 1,
            loading: false,
            dialogAddOrMod: '',
            dialogTitle: '',
            dialogAddFormVisible: false,
            formLabelWidth: '120px',
            roleAvailableOperate:[], //保存的是修改角色的已有权限
            mroleName: '',
            mroleType: '',
            userTypeOptions: [     // 用户类型data
                { text: '系统管理', value: 'A' },
                { text: '安全管理', value: 'B' },
                { text: '业务办理', value: 'C' },
                { text: '审计管理', value: 'D' }
            ],
            userRoleOperations: [],

            roleOperate:[],
            addForm: {
                roleName: '',
                rolePrems: '',
                roleType: ''    ,
                rid: ''
            },
            searchForm: {
                roleId: '',
                pageNum: 1,
                pageSize: 10000
            },
            tableData: {
                head: [
                {
                key: 'rid',
                name: '角色ID'
                },
                {
                key: 'roleName',
                name: '角色名称'
                },
                {
                    key: 'roleTypeName',
                    name: '角色类型'
                },
                {
                    key: 'perList',
                    name: '操作权限'
                }
                ],
                body: []
            },
            addRules: {
                roleName: [
                    {required: true, validator: validateRoleName, trigger: 'blur' }
                ],
                roleType: [
                    {required: true, validator: validateRoleType, trigger: 'blur' }
                ]
            }
        }
    },
    mounted() {
      this.controlObj.createIcon = 'el-icon-circle-plus-outline'
      this.controlObj.createMsg = '新增角色'
      this.controlObj.createVisibleFlag = false
        this.findAll()
        this.checkData()
        //this.getExistRoleData()
    },

    methods: {
        checkData(){
            this.HTTP.methods.apiGet("/role/safe.shtml").then(res =>
            {
               if(res.data == false){

                    this.$notify({
                      title: '警告',
                      message: '您访问的这张表数据不完整，记录被删除过'

                    });
               }

            }
        )
        },
         refresh(){
            this.findAll()
            // this.checkData()
        },
        typeFormatter : function (row, column, cellValue) {
            if(row.roleType.indexOf("A")>-1){
                return "系统管理"
            }else if(row.roleType.indexOf("B")>-1){
                return "安全管理";
            }else if(row.roleType.indexOf("C")>-1){
                return "业务管理"
            }else if(row.roleType.indexOf("D")>-1){
                return "审计管理"
            }
        },
          //每页显示数据量变更
        handleSizeChange: function(val) {
            this.pageSize = val;
            this.findAll()
        },

        //页码变更
        handleCurrentChange: function(val) {
            this.pageNum = val;
            this.findAll()
        },
        //通过选择获取权限列表
        currentSel(val){
            let data = {
                params: {}
            }
            data.params = {psType:val}
            if(this.addForm.roleType == val){
                this.roleOperate = this.addForm.rolePrems.split(',')
            }else{
                this.roleOperate = []
            }
            this.HTTP.methods.apiGet("/permission/find", data).then(res =>
            {
                if(res.code != 200){
                    this.$message.error(res.msg)
                }else{
                    // this.tableData.head = res.head
                    var groupName = 'group' + val
                    this.userRoleOperations = (res.data)[groupName]
                }
            }).catch(err => {
            this.$message.error(`获取数据失败`)
            })

        },
        tableRowClassName({row, rowIndex}) {
          if(row.safe == false){
            return 'warning-row';
          }else{
              return 'success-row'
          }
        },
        confirmDelete(item) {
        this.$confirm('确认删除该角色?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          center: true,
          type: 'warning'
        }).then(() => {
            this.loading = true;
            this.HTTP.methods.apiPost('/role/delete', {rid: item.rid}).then((res) => {

                if(res.code==200) {
                    this.$message({
                        message: res.msg,
                        type: 'success'
                    })
                    for(let i=0; i<this.tableData.body.length; i++){
                        if(item.rid == this.tableData.body[i].rid){
                            this.tableData.body.splice(i, 1)
                        }
                    }
                }else {
                    this.$message({
                        message: res.msg,
                        type: 'error'
                    })
                }
                this.loading = false;
            })
        })
      },
        onSelect(val){
            //this.addForm.rolePrems = this.roleOperate.join(',')
        },
        editRole(item){
            // this.addForm.roleName =  item.roleName
            // this.addForm.roleType =  item.roleType
            // this.addForm.rid = item.rid
            // this.addForm.rolePrems = item.rolePrems
            this.addForm = item;
            //this.addForm.roleOperation =  obj[index].roleOperation
            this.currentSel(item.roleType)
            this.roleOperate = item.rolePrems.split(',')
            this.dialogAddOrMod = 'mod'
            this.dialogTitle = '修改角色'

            this.mroleName = item.roleName
            this.mroleType = item.roleType

            this.dialogAddFormVisible = true

        },

        singleAdd() {
            for (var i in this.addForm) {
            (this.addForm)[i] = ''
            }
            this.dialogAddOrMod = 'add'
            this.dialogTitle = '新增角色'
            this.dialogAddFormVisible = true
      },
      singleAddCommit() {
        this.$refs.addForm.validate((valid) => {
          if (valid) {
            if(this.roleOperate.length == 0){
                this.$message({
                        message: "权限不能为空",
                        type: 'error'
                })
                return;
            }
            let obj = {
                'roleType': this.mroleType,
                'roleName': this.mroleName,
                'rolePrems': this.roleOperate.join(',')
            }
            this.loading = true // 禁止再次点击
            this.HTTP.methods.apiPost('/role/insert',obj).then((res) => {
              if (res.code != 200) {
                this.$message({
                        message: res.msg,
                        type: 'error'
                })
              } else {
                  this.$message({
                        message: res.msg,
                        type: 'success'
                })
                setTimeout(() => {
					this.reload()
                }, 2000)
              }
              this.loading = false
            })
          } else {
            return false
          }
        })
      },
      singleModCommit(){
          this.$refs.addForm.validate((valid) => {
          if (valid) {
            if(this.roleOperate.length == 0){
                this.$message({message: '权限不能为空', type: 'warning'})
                return;
            }
            let msg = {
                'roleName': this.mroleName,
                'roleType': this.mroleType,
                'rid': this.addForm.rid,
                'rolePrems': this.roleOperate.join(',')
            }
            this.loading = true // 禁止再次点击
            this.HTTP.methods.apiPut('/role/modify',msg).then((res) => {
              if (res.code != 200) {
                this.$message({
                        message: res.msg,
                        type: 'error'
                })
              } else {
                  this.$message({
                        message: res.msg,
                        type: 'success'
                })
                for(let i=0; i<this.tableData.body.length; i++){
                    if(this.tableData.body[i].rid == msg.rid){
                        this.tableData.body[i].roleName = msg.roleName;
                        this.tableData.body[i].roleType = msg.roleType;
                        this.tableData.body[i].rolePrems = msg.rolePrems
                    }
                }
                this.dialogAddFormVisible  = false
              }
              this.loading = false
            })
          } else {
            return false
          }
        })
      },
        // 获取当前系统全部Role数据，不分页。
        // Api: /api/{version}/permission/findll
        findAll() {
            let data = {
                params: {}
            }
            data.params = {pageNum:this.pageNum, pageSize:this.pageSize}
            this.HTTP.methods.apiGet("/role/page", data).then(res =>
            {
                if(res.code != 200){
                    this.tableData.body = []
                    this.$message.error(res.msg)
                     this.totalCount = 0

                }else{
                    this.tableData.body = res.data.rows
                  console.log(this.tableData.body)
                     this.totalCount = res.data.total
                     this.checkData()
                }
                this.loading = false
            }).catch(err => {
                this.$message.error('网络超时')
                this.loading = false
                this.totalCount = 0
            })
        },

        getExistRoleData() {
            this.$axios({
                url: '/roleDataList',
                type: 'post',
                data: {}
            }).then(res => {
                this.loading = false
                this.tableData.head = res.head
                this.tableData.body = res.body
                //console.log( res.body)
            }).catch(err => {
                this.$message.error(`获取数据失败，失败码：${err.response.status}`)
            })
        },
        search(){
            let data = {
                params: {}
            }
            data.params = this.searchForm
            if(this.searchForm.roleId == '') {
                this.findAll()
                return
            }
            this.HTTP.methods.apiGet("/role/find", data).then(res =>
            {
                if(res.code != 200){
                    this.tableData.body = []
                    // this.tableData.head = []
                    this.loading = true
                    this.$message.error(res.msg)

                }else{
                    // this.tableData.head = res.head
                    this.tableData.body = res.data.rows
                    // for (var i  in this.tableData.body) {
                    //     if (this.tableData.body[i].roleType) {
                    //         this.tableData.body[i].roleTypeName =
                    //             this.GLOBAL.getRoleTypeName(this.tableData.body[i].roleType)
                    //         this.tableData.body[i].perList =
                    //             this.GLOBAL.getPermListFromStr(this.tableData.body[i].rolePrems).join(',')
                    //     }
                    // }

                    this.loading = false
                }
            }).catch(err => {
            this.$message.error(`获取数据失败`)
            })

        }
    }
}
</script>
<style>
  .el-table .warning-row {
    background: #F08080;
  }

  .el-table .success-row {
    background:#f0f9eb;
  }

  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 130px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 33%;
  }
</style>
